package cn.lili.modules.promotion.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.client.GoodsSkuClient;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.promotion.entity.dos.ReturnActivity;
import cn.lili.modules.promotion.entity.dos.ReturnActivityGoods;
import cn.lili.modules.promotion.entity.enums.ReturnActivityFreezeEnum;
import cn.lili.modules.promotion.entity.enums.ReturnActivityStatusEnum;
import cn.lili.modules.promotion.mapper.ReturnActivityGoodsMapper;
import cn.lili.modules.promotion.service.ReturnActivityGoodsService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ReturnActivityGoodsServiceImpl extends ServiceImpl<ReturnActivityGoodsMapper, ReturnActivityGoods> implements ReturnActivityGoodsService {

    @Resource
    private GoodsClient goodsClient;

    private final GoodsSkuClient goodsSkuClient;

    /**
     * 获取全返卷商品列表
     *
     * @param page       分页条件
     * @param queryParam 查询条件
     */
    @Override
    public Page<ReturnActivityGoods> getPage(ReturnActivityGoods queryParam, PageVO page) {
        //构建查询条件
        LambdaQueryWrapper<ReturnActivityGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReturnActivityGoods::getDeleteFlag,false);
        queryWrapper.likeRight(StringUtils.isNotEmpty(queryParam.getGoodsName()),ReturnActivityGoods::getGoodsName,queryParam.getGoodsName());
        queryWrapper.eq(StringUtils.isNotEmpty(queryParam.getGoodsId()), ReturnActivityGoods::getGoodsId,queryParam.getGoodsId());
        queryWrapper.eq(StringUtils.isNotEmpty(queryParam.getStatus()),ReturnActivityGoods::getStatus,queryParam.getStatus());
        queryWrapper.eq(StringUtils.isNotEmpty(queryParam.getStoreId()),ReturnActivityGoods::getStoreId,queryParam.getStoreId());
        queryWrapper.likeRight(StringUtils.isNotEmpty(queryParam.getStoreName()),ReturnActivityGoods::getStoreName,queryParam.getStoreName());
        queryWrapper.orderByDesc(ReturnActivityGoods::getCreateTime);
        //查询
        return this.baseMapper.selectPage(PageUtil.initPage(page), queryWrapper);
    }

    /**
     * 添加全返卷商品
     * @param saveParams 添加参数
     * @param currentUser 用户信息
     * @return 成功/失败
     * */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean saves(List<ReturnActivityGoods> saveParams, AuthUser currentUser) {
        if (saveParams.isEmpty()) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        // 判断是否有重复商品
        String msg = existReturnGoodsSku(saveParams);
        if (CharSequenceUtil.isNotEmpty(msg)) {
            throw new ServiceException(msg);
        }

        List<String> goodsIds = saveParams.stream().map(ReturnActivityGoods::getGoodsId).toList();

        // 判断全返商品是否已存在
        String result = existReturnGoods(goodsIds);
        if (CharSequenceUtil.isNotEmpty(result)) {
            throw new ServiceException(result);
        }

        //新增全返卷商品
        List<ReturnActivityGoods> goodsList = saveParams.stream().peek(e->{
            e.setStoreId(currentUser.getExtendId());
            e.setStoreName(currentUser.getExtendName());
            e.setStatus(ReturnActivityFreezeEnum.NORMAL.getCode());
            e.setId(SnowFlake.getIdStr());
        }).toList();
        boolean b = super.saveBatch(goodsList);

        //清除goods缓存
        goodsClient.cleanGoodsCache(goodsIds);

        //更新商品全返状态
        goodsClient.updateResultGoods(goodsIds,true);

        // 重新设置商品sku缓存
        goodsSkuClient.updateGoodsSkuCache(goodsIds);

        return b;
    }

    private String existReturnGoodsSku(List<ReturnActivityGoods> saveParams) {
        Map<String, List<ReturnActivityGoods>> collect = saveParams.stream().collect(Collectors.groupingBy(ReturnActivityGoods::getGoodsId));
        StringBuffer sb = new StringBuffer();
        collect.forEach((key, value) -> {
            if (value.size() > 1) {
                value.forEach(returnActivityGoods -> {
                    sb.append("【").append(returnActivityGoods.getGoodsName()).append("】");
                });
            }
        });
        if (CharSequenceUtil.isNotEmpty(sb.toString())) {
            sb.append("重复商品SKU,请删除后再添加");
        }
        return sb.toString();
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean freeze(String id,String remark) {
        ReturnActivityGoods returnActivityGoods = getById(id);
        if(returnActivityGoods == null){
            return false;
        }
        //更新商品全返状态
        List<String> goodsIds = Collections.singletonList(returnActivityGoods.getGoodsId());
        //更新全返卷商品
        returnActivityGoods.setStatus(ReturnActivityFreezeEnum.FREEZE.getCode());
        returnActivityGoods.setRemark(remark);
        boolean b = updateById(returnActivityGoods);
        //清除goods缓存
        goodsClient.cleanGoodsCache(goodsIds);

        //更新商品全返状态
        goodsClient.updateResultGoods(goodsIds,false);

        // 重新设置商品sku缓存
        goodsSkuClient.updateGoodsSkuCache(goodsIds);
        return b;
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean unfreeze(String id,String remark) {
        ReturnActivityGoods returnActivityGoods = getById(id);
        if(returnActivityGoods == null){
            return false;
        }
        //更新商品全返状态
        List<String> goodsIds = Collections.singletonList(returnActivityGoods.getGoodsId());

        //更新全返卷商品
        returnActivityGoods.setStatus(ReturnActivityFreezeEnum.NORMAL.getCode());
        returnActivityGoods.setRemark(remark);
        boolean b = updateById(returnActivityGoods);
        //清除goods缓存
        goodsClient.cleanGoodsCache(goodsIds);

        //更新商品全返状态
        goodsClient.updateResultGoods(goodsIds,true);

        // 重新设置商品sku缓存
        goodsSkuClient.updateGoodsSkuCache(goodsIds);
        return b;
    }

    /**
     * 删除全返卷商品
     * @param id 全返卷ID
     * @return 成功/失败
     * */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean removeById(Serializable id) {
        ReturnActivityGoods returnActivityGoods = getById(id);
        if(returnActivityGoods == null){
            return false;
        }
        //更新商品全返状态
        List<String> goodsIds = Collections.singletonList(returnActivityGoods.getGoodsId());

        //清除goods缓存
        goodsClient.cleanGoodsCache(goodsIds);

        //更新商品全返状态
        goodsClient.updateResultGoods(goodsIds,false);

        // 重新设置商品sku缓存
        goodsSkuClient.updateGoodsSkuCache(goodsIds);

        //删除全返卷商品
        return super.removeById(id);
    }

    /**
     * 根据goodsId查询全返商品
     * @param goodsId
     * @return
     */
    private String existReturnGoods (List<String> goodsId) {
        LambdaQueryWrapper<ReturnActivityGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ReturnActivityGoods::getGoodsId, goodsId);
        queryWrapper.eq(ReturnActivityGoods::getStoreId, Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
        List<ReturnActivityGoods> returnActivityGoodsList = this.list(queryWrapper);
        if (!returnActivityGoodsList.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            sb.append("存在重复商品，");
            returnActivityGoodsList.forEach(returnActivityGoods -> {
                sb.append("【").append(returnActivityGoods.getGoodsName()).append("】");
            });
            sb.append("请删除后再添加");
            return sb.toString();
        }
        return null;
    }

    /**
     * 根据商品ID判断是否全返商品
     * @param goodsId
     * @return
     */
    @Override
    public boolean isReturnActivityGoods (String goodsId) {
        LambdaQueryWrapper<ReturnActivityGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReturnActivityGoods::getGoodsId, goodsId);
        queryWrapper.eq(ReturnActivityGoods::getStatus, 0);
        long count = this.count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据店铺ID获取店铺的全返商品
     * @param store
     * @return
     */
    @Override
    public List<ReturnActivityGoods> getListByStore (String store) {
        LambdaQueryWrapper<ReturnActivityGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReturnActivityGoods::getStoreId, store);
        return this.list(queryWrapper);
    }
}
